package com.dub.utils;

import android.os.AsyncTask;
import android.provider.ContactsContract;

import com.dub.iterface.ISessionHandle;
import com.dub.model.SecRpcModel;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Session implements Runnable{
    static Session ses = null;
    //代理的信息
    SecRpcModel.ModelSecRpcAgentResLogin  agent=null;
    //处理接口的集合，一个类只可以有一个处理接口
    Map<String,ISessionHandle> handls=new HashMap<String,ISessionHandle>();

    //添加一个命令处理接口
    public void AddHand(String key, ISessionHandle hand){
        handls.put(key,hand);
    }

    public SecRpcModel.ModelSecRpcAgentResLogin GetAgent(){
        return agent;
    }
    public static Session GetSession() {
        if (ses!=null){
            return ses;
        }
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    ses = new Session("192.168.31.226",10167);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
        return ses;
    }

    /**
     * 判断链接是否断开
     * */
    public static boolean IsClose(){
        if (ses==null){
            return true;
        }
        return ses.socket.isClosed();
    }

    private Socket socket;
    private OutputStream ops;
    private InputStream ips;
    private Thread thread;
    private Session(String addr,int port) throws IOException {
        socket=new Socket(addr,port);
        ops=socket.getOutputStream();
        ips=socket.getInputStream();

        thread=new Thread(this);
        thread.start();

        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    while(true){
                        ses.Send((short)0,(short)0,null);
                        Thread.sleep(8000);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 发送数据
     * @param mainId 主命令
     * @param subId 子命令
     * @param data 数据
     * @return true成功 false失败
     * */
    public boolean Send(short mainId, short subId, byte[] data) {
        try{
            int start_count=0;
            int byte_count=12;
            if (data!=null&&data.length>0){
                byte_count+=data.length;
            }
            byte[] allData=new byte[byte_count];
            byte[] mainData=ByteConvert.shortToBytes(mainId);
            byte[] subData=ByteConvert.shortToBytes(subId);
            byte[] lengthData=ByteConvert.longToBytes(new Long(byte_count));

            allData=this.addByte(allData,lengthData,start_count);
            start_count+=lengthData.length;
            allData=this.addByte(allData,mainData,start_count);
            start_count+=mainData.length;
            allData=this.addByte(allData,subData,start_count);
            start_count+=subData.length;
            if (data!=null&&data.length>0){
                allData=this.addByte(allData,data,start_count);
            }

            ops.write(allData);
            ops.flush();
        }catch(IOException e){
            e.printStackTrace();
        }
        return true;
    }

    private byte[] addByte(byte[] all,byte[] data, int startIndex){
        for (int i=0;i<data.length;i++){
            all[i+startIndex]=data[i];
        }
        return all;
    }

    public boolean Close() throws IOException {
        if (socket!=null){
            socket.close();
        }
        return true;
    }

    public void run() {
        try{
            while(true){
                byte[] size_data=new byte[8];
                if (ips.read(size_data)>0){
                    long size=ByteConvert.bytesToLong(size_data);
                    byte[] info_byte=new byte[((int)size)-8];
                    if (ips.read(info_byte)>0){
                        byte[] main_data=new byte[2];
                        System.arraycopy(info_byte,0,main_data,0,2);
                        short mainId=ByteConvert.bytesToShort(main_data);

                        byte[] sub_data=new byte[2];
                        System.arraycopy(info_byte,2,sub_data,0,2);
                        short subId=ByteConvert.bytesToShort(sub_data);

                        byte[] data=new byte[info_byte.length-4];
                        System.arraycopy(info_byte,4,data,0,data.length);

                        //判断消息类型
                        if (mainId==1&&subId==1){
                            try{
                                SecRpcModel.ModelSecRpcAgentResLogin mdl=SecRpcModel.ModelSecRpcAgentResLogin.newBuilder().mergeFrom(data).build();
                                agent=mdl;
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }

                        //回调命令处理方法
                        adaterHandle(mainId,subId,data);
                    }
                }
            }
        }catch(IOException e){
            android.util.Log.i("[session]",e.getMessage());
        }
    }

    private void adaterHandle(int mainId, int subId, byte[] data){
        if (mainId==0&&subId==0){
            return;
        }
        String cmd_str=mainId+"-"+subId;
        int count_handle=handls.size();
        Iterator<ISessionHandle> iter_handles= handls.values().iterator();
        while (iter_handles.hasNext()){
            ISessionHandle handle=iter_handles.next();
            if (handle.GetHandCmd().contains(cmd_str)){
                handle.HandAction(cmd_str,data);
            }
        }
    }
}